package com.xywang.controller;

import com.xywang.pojo.Books;
import com.xywang.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

@Controller
@RequestMapping("/book")
public class BookController {
    private BookService bookServiceImpl;
    @Autowired
    @Qualifier("bookServiceImpl")
    public void setBookService(BookService bookServiceImpl) {
        this.bookServiceImpl = bookServiceImpl;
    }

    @RequestMapping("/selectAllBooks")
    public String selectAllBooks(Model model){
        List<Books> books = bookServiceImpl.selectAllBooks();
        model.addAttribute("bookList",books);
        return "bookList";
    }
    // 增
    @RequestMapping("/toAddBook")
    public String toAddBook(){
        return "addBook";
    }
    @RequestMapping("/addBook")
    public String addBook(Books books){
        int i = bookServiceImpl.addBook(books);
        if(i>0){
            return "redirect:/book/selectAllBooks";
        }
        return "error";
    }
    // 删
    @RequestMapping("/deleteBook/{id}")
    public String deleteBook(@PathVariable int id){
        int i = bookServiceImpl.deleteBook(id);
        if(i>0){
            return "redirect:/book/selectAllBooks";
        }
        return "error";
    }
    // 改
    @RequestMapping("/toUpdateBook")
    public String toUpdateBook(int id,Model model){
        Books books = bookServiceImpl.selectBookByID(id);
        model.addAttribute("Qbook",books);
        return "updateBook";
    }
    @RequestMapping("/updateBook")
    public String updateBook(Books books){
        int i = bookServiceImpl.updateBook(books);
        if(i>0){
            return "redirect:/book/selectAllBooks";
        }
        return "error";
    }
    // 按名字查
    @RequestMapping("/selectBook")
    public String selectBooksByName(String selectBookByName,Model model){
        List<Books> books = bookServiceImpl.selectBooksByName(selectBookByName);
        if(books.size()==0){
            model.addAttribute("error","未查询到此书！");
        }
        model.addAttribute("bookList",books);
        return "bookList";
    }
}
